<template>
    <Layout style="height: 100%">
        <Sider hide-trigger collapsible :width="256" :style="{overflow: 'hidden'}">
            <Menu ref="menu" width="auto" @on-select="turnToPage">
                <MenuItem name="home">首页</MenuItem>
                <MenuItem name="chat">聊天</MenuItem>
                <MenuItem name="logout">退出</MenuItem>
            </Menu>
        </Sider>
        <Layout>
            <Content>
                <router-view/>
            </Content>
        </Layout>
    </Layout>
</template>
<script>
    import {mapActions} from 'vuex'
    import WebIM from '@/easemob/web-im';
    export default {
        name: 'Main',
        components: {},
        data() {
            return {}
        },
        computed: {},
        methods: {
            turnToPage(name) {
                if (name === 'logout') {
                    this.logout();
                    return;
                }
                this.$router.push({
                    name,
                });
            },
            logout () {
                localStorage.clear();
                this.$router.push({
                    name: 'login',
                })
            },
            initWebIm() {
                let vm = this;
                this.$im.conn.open({
                    apiUrl: this.$im.config.apiURL,
                    appKey: this.$im.config.appkey,
                    user: this.$util.getWebImUsername(),
                    accessToken: this.$util.getWebImToken()
                });
                this.$im.conn.listen({
                    // 连接成功
                    onOpened: function (message) {
                        console.log('连接成功');
                        vm.$store.commit('SET_WEB_IM_CONN_STATE', true);
                    },
                    // 连接关闭
                    onClosed: function () {
                        console.log('连接关闭');
                        vm.$store.commit('SET_WEB_IM_CONN_STATE', false);
                    },
                    onFileMessage: function (message) {
                        vm.$store.commit('SET_WEB_IM_MESSAGE',
                            {
                                id: message.id,
                                isSelf: false,
                                type: vm.$im.msgType.file.value,
                                username: message.from,
                                content: message.url
                            });
                        vm.webImNotify(message.from + '：' + vm.$im.msgType.file.desc, '');
                    },
                    onVideoMessage: function (message) {
                        let option = {
                            url: message.url,
                            headers: {
                                'Accept': 'audio/mp4'
                            },
                            onFileDownloadComplete: function (response) {
                                let url = WebIM.utils.parseDownloadResponse.call(vm.$im.conn, response);
                                vm.$store.commit('SET_WEB_IM_MESSAGE',
                                    {
                                        id: message.id,
                                        isSelf: false,
                                        type: vm.$im.msgType.video.value,
                                        username: message.from,
                                        content: url
                                    });
                                vm.webImNotify(message.from + '：' + vm.$im.msgType.video.desc, '');
                            },
                            onFileDownloadError: function () {

                            }
                        };
                        WebIM.utils.download.call(vm.$im.conn, option);
                    },
                    onAudioMessage: function (message) {
                        let options = {url: message.url};
                        // 音频下载成功
                        options.onFileDownloadComplete = function (response) {
                            let url = WebIM.utils.parseDownloadResponse.call(vm.$im.conn, response);
                            vm.$store.commit('SET_WEB_IM_MESSAGE',
                                {
                                    id: message.id,
                                    isSelf: false,
                                    type: vm.$im.msgType.audio.value,
                                    username: message.from,
                                    content: url
                                });
                            vm.webImNotify(message.from + '：' + vm.$im.msgType.audio.desc, '');
                        };
                        options.onFileDownloadError = function () {

                        };
                        options.headers = {
                            'Accept': 'audio/mp3'
                        };
                        WebIM.utils.download.call(vm.$im.conn, options);
                    },
                    onPictureMessage: function (message) {
                        vm.$store.commit('SET_WEB_IM_MESSAGE',
                            {
                                id: message.id,
                                isSelf: false,
                                type: vm.$im.msgType.img.value,
                                username: message.from,
                                content: message.url
                            });
                        vm.webImNotify(message.from + '：' + vm.$im.msgType.img.desc, message.url);
                    },
                    onTextMessage: function (message) {
                        vm.$store.commit('SET_WEB_IM_MESSAGE',
                            {
                                id: message.id,
                                isSelf: false,
                                type: vm.$im.msgType.txt.value,
                                username: message.from,
                                content: message.data
                            });
                        vm.webImNotify(message.from + '：' + message.data, '');
                    },
                    // 处理广播或发布-订阅的消息
                    onPresence: function (message) {

                    },
                    // 收到消息送达服务器回执
                    onReceivedMessage: function (message) {
                    },
                    // 收到消息送达客户端回执
                    onDeliveredMessage: function (message) {

                    },
                    // 收到消息已读回执
                    onReadMessage: function (message) {

                    },
                    // 失败回调
                    onError: function (error) {
                        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_DISCONNECTED) {
                            console.log(
                                'WEBIM_CONNCTION_DISCONNECTED',
                                WebIM.conn.autoReconnectNumTotal,
                                WebIM.conn.autoReconnectNumMax
                            )
                            if (WebIM.conn.autoReconnectNumTotal < WebIM.conn.autoReconnectNumMax) {
                                return
                            }
                            console.log('serverSideCloseWebsocketConnection')
                            return
                        }
                        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_AUTH_ERROR) {
                            console.log('webIMConnectionAuthError')
                            return
                        }
                        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_CLOSE_ERROR) {
                            console.log('WEBIM_CONNCTION_SERVER_CLOSE_ERROR')
                            return
                        }
                        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_SERVER_ERROR) {
                            console.log('offlineByMultiLogin')
                            return
                        }
                        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_USER_REMOVED) {
                            console.log('用户下线')
                            return
                        }
                        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_USER_LOGIN_ANOTHER_DEVICE) {
                            if (vm.$route.name === 'chat') {
                                alert('账户在另外一台设备登录')
                            }
                            console.log('账户在另外一台设备登录')
                            return
                        }
                        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_USER_KICKED_BY_CHANGE_PASSWORD) {
                            console.log('用户修改密码')
                            return
                        }
                        if (error.type == WebIM.statusCode.WEBIM_CONNCTION_USER_KICKED_BY_OTHER_DEVICE) {
                            console.log('用户被其他设备踢掉')
                            return
                        }
                        if (error.type == 1) {
                            let data = error.data ? error.data.data : ''
                            console.log(data)
                        }
                    }
                });
            },
            webImNotify(data, url) {
                let routerName = 'custom-chat';
                if (this.$route.name !== routerName) {
                    let notify = this.$util.createNotification('您有有新的聊天消息，请查收', 'chat', data, url, 3000);
                    if (notify) {
                        notify.onclick = () => {
                            this.$router.push({
                                name: routerName
                            });
                        };
                    }
                }
            }
        },
        mounted() {
            this.initWebIm();
        }
    }
</script>
